#include <iostream>
#include <signal.h>


#include "../common/httplib.h"
#include "oj_control.hpp"



using namespace httplib;
using namespace ns_control;
static Control* ctrl_ptr = nullptr;

void Recovery(int signo){
    ctrl_ptr->RecoveryMachine();
}

int main(){
    signal(SIGQUIT,Recovery);
    // 用户请求的服务路由功能(用户可能请求首页、论坛、测试代码)
    Server svr;
    Control ctrl;
    ctrl_ptr = &ctrl;

    // 设置一下网站的首页
    svr.set_base_dir("./wwwroot");
    // 获取所有的题目列表
    svr.Get("/all_questions",[&ctrl](const Request & req, Response & resp){
        // resp.set_content("这是所有题目的列表","text/plain; charset=utf-8");
        // 返回一张有所有题目的html网页
        std::string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html,"text/html; charset=utf-8");
    });
    // 根据题目编号，获取相应的题目内容
    svr.Get(R"(/question/(\d+))",[&ctrl](const Request & req, Response & resp){
        std::string number = req.matches[1];
        // resp.set_content("这是指定的一道题："+ number,"text/plain; charset=utf-8");
        std::string html;
        ctrl.Question(number,&html);
        resp.set_content(html,"text/html; charset=utf-8");
    });
    // 用户提交代码，使用判题功能
    svr.Post(R"(/judge/(\d+))",[&ctrl](const Request & req, Response & resp){
        std::string number = req.matches[1];
        // resp.set_content("指定题目的判题："+ number,"text/plain; charset=utf-8");
        std::string out_json;
        ctrl.Judge(number,req.body,&out_json);
        resp.set_content(out_json,"application/json; chatset=utf-8");
    });
    svr.listen("0.0.0.0",8080);
    return 0;
}